package com.example.yinweiapplication.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.yinweiapplication.Bean.HomeBean;
import com.example.yinweiapplication.R;
import com.example.yinweiapplication.adapter.HomePtrLvAdapter;
import com.example.yinweiapplication.config.UrlsConfig;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class HomeFragment extends BaseFragment {
    private HttpUtils httpUtils;
    @ViewInject(R.id.home_fragment_ptrlistview)
    private PullToRefreshListView ptrlistview;
    private HomePtrLvAdapter adapter;
    private List<HomeBean.DataEntity.App_index_recommandEntity> list;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         View view = inflater.inflate(R.layout.home_fragment_layout,null);
        ViewUtils.inject(this,view);
        initAdapter();
        loadData();
        return view;
    }

    private void loadData() {
        httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.POST, UrlsConfig.HOME_URL, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String json = responseInfo.result;
                HomeBean homeBean = JSON.parseObject(json, HomeBean.class);
                List<HomeBean.DataEntity.App_index_recommandEntity> list1 = homeBean.getData().getApp_index_recommand();
                list.addAll(list1);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getActivity(),"加载数据失败",Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void initAdapter(){
        list = new ArrayList<>();
        adapter = new HomePtrLvAdapter(list,getActivity());
        ptrlistview.setAdapter(adapter);
    }
}
